package com.aerfazhe.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * @Author：wk
 * @Slogan：无论风雨，和自己一决胜负吧
 * @Create：2022/6/30/14:20
 * @Description：自定义过滤器工厂
 * @Version：1.0
 */
@Component
@Slf4j
public class CheckAuthGatewayFilterFactory extends AbstractGatewayFilterFactory<CheckAuthGatewayFilterFactory.Config> {

    /**
     * VALUE key.
     */
    public static final String VALUE = "value";

    public CheckAuthGatewayFilterFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList(VALUE);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            String name = exchange.getRequest().getQueryParams().getFirst("name");
            log.info("name======"+name);
            if (StringUtils.isNotBlank(name)) {
                if (config.getValue().equals(name)) {
                    return chain.filter(exchange);
                }
                else {
//                    返回404
                    exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND);
                    return exchange.getResponse().setComplete();
                }
            }
//            正常请求
            return chain.filter(exchange);
        };
    }

    public static class Config {
        private String value;

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }

}
